<template>
  <wd-select-picker
    v-model="selectedValue"
    :columns="categoryOptions"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    @confirm="handleSelect"
    @clear="handleClear"
  >
    <wd-cell
      :title="displayText || placeholder"
      :value="displayText"
      :placeholder="placeholder"
      is-link
      :disabled="disabled"
    />
  </wd-select-picker>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'

interface Category {
  id: number
  name: string
  parentId?: number
  children?: Category[]
}

interface Props {
  modelValue?: number | string
  placeholder?: string
  disabled?: boolean
  clearable?: boolean
  size?: 'large' | 'default' | 'small'
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  placeholder: '请选择分类',
  disabled: false,
  clearable: true,
  size: 'default',
})

const emit = defineEmits<{
  'update:modelValue': [value: number | string | undefined]
  change: [value: number | string | undefined, option?: Category]
}>()

// 响应式数据
const selectedValue = ref<number | string | undefined>(props.modelValue)
const categories = ref<Category[]>([])
const loading = ref(false)

// 计算属性
const categoryOptions = computed(() => {
  return categories.value.map((category) => ({
    value: category.id,
    label: category.name,
    children: category.children?.map((child) => ({
      value: child.id,
      label: child.name,
    })),
  }))
})

const displayText = computed(() => {
  if (!selectedValue.value) return ''

  const findCategory = (cats: Category[], id: number | string): Category | undefined => {
    for (const cat of cats) {
      if (cat.id == id) return cat
      if (cat.children) {
        const found = findCategory(cat.children, id)
        if (found) return found
      }
    }
    return undefined
  }

  const category = findCategory(categories.value, selectedValue.value)
  return category?.name || ''
})

// 监听props变化
watch(
  () => props.modelValue,
  (newVal) => {
    selectedValue.value = newVal
  },
)

// 事件处理
const handleSelect = (value: any) => {
  selectedValue.value = value[0]
  emit('update:modelValue', selectedValue.value)

  const findCategory = (cats: Category[], id: number | string): Category | undefined => {
    for (const cat of cats) {
      if (cat.id == id) return cat
      if (cat.children) {
        const found = findCategory(cat.children, id)
        if (found) return found
      }
    }
    return undefined
  }

  const category = findCategory(categories.value, selectedValue.value)
  emit('change', selectedValue.value, category)
}

const handleClear = () => {
  selectedValue.value = undefined
  emit('update:modelValue', undefined)
  emit('change', undefined)
}

// 获取分类列表
const loadCategories = async () => {
  loading.value = true
  try {
    // TODO: 调用实际的API接口获取分类列表
    // const response = await getCategoryListApi()
    // categories.value = response.data || []

    // 暂时使用模拟数据
    categories.value = [
      {
        id: 1,
        name: '医疗器械',
        children: [
          { id: 11, name: '监护设备', parentId: 1 },
          { id: 12, name: '手术器械', parentId: 1 },
        ],
      },
      {
        id: 2,
        name: '防护用品',
        children: [
          { id: 21, name: '口罩', parentId: 2 },
          { id: 22, name: '防护服', parentId: 2 },
        ],
      },
      {
        id: 3,
        name: '药品耗材',
        children: [
          { id: 31, name: '急救药品', parentId: 3 },
          { id: 32, name: '医用耗材', parentId: 3 },
        ],
      },
    ]
  } catch (error) {
    console.error('获取分类列表失败:', error)
    uni.showToast({
      title: '获取分类列表失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadCategories()
})

defineOptions({
  name: 'CategorySelect',
})
</script>

<style lang="scss" scoped>
// Apple 风格样式
:deep(.wd-cell) {
  padding: 14px 16px;
  background-color: #ffffff;
  border-radius: 12px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;

  &:hover {
    border-color: #007aff;
    box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
  }

  &.is-disabled {
    opacity: 0.6;
    background-color: #f2f2f7;
  }
}

:deep(.wd-cell__title) {
  color: #1d1d1f;
  font-weight: 500;
  font-size: 16px;
}

:deep(.wd-cell__value) {
  color: #8e8e93;
  font-size: 15px;
}
</style>
